<template>
  <div v-loading="loading">
    <i class="el-icon-back wl-back" @click="handleBack()"> 返回</i>

    <!-- 项目添加成员 -->
    <el-card class="box-card wl-card">
      <div slot="header" class="clearfix">
        <span>添加成员</span>
      </div>
      <el-form ref="mbform" :model="mbform" :rules="mbformRules" label-width="90px">
        <el-form-item label="成员名称" prop="userId">
          <el-select v-model="mbform.userId" placeholder="搜索添加用户" filterable class="wl-input" @focus="handleFocusUsers()" @keyup.native="handleInputUserName">
            <el-option v-for="item in userList" :key="item.user_id" :label="item.username" :value="item.user_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成员角色" prop="role">
          <el-select v-model="mbform.role" placeholder="请分配角色" class="wl-input">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button @click="handleAddProjectMember()" type="primary" icon="el-icon-plus" class="wl-append">添加</el-button>
    </el-card>

    <!-- 成员列表 -->
    <el-card class="box-card wl-card">
      <div slot="header" class="clearfix">
        <span>成员列表({{ members.length }})</span>
      </div>
      <el-table :data="members" :show-header="false" class="wl-table">
        <el-table-column prop="username" label="用户名" width="200">
          <template slot-scope="scope">
            <div class="wl-avatar">
              <span><img :src="'/static/assets' + scope.row.avatar" alt="" /></span>
              <span style="margin-left: 10px">{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="成员角色">
          <template slot-scope="scope"><span>{{getMemberRole(scope.row.role)}}</span></template>
        </el-table-column>
        <el-table-column prop="operate" label="操作">
          <template slot-scope="scope">
            <div class="wl-right">
              <el-button v-if="enableUpdate" @click="handleEdit(scope.row)" type="primary" icon="el-icon-edit" circle></el-button>
              <el-button v-if="enableDelete" @click="handleDelete(scope.row)" type="danger" icon="el-icon-delete" class="wl-delete" circle></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑成员 -->
    <el-dialog title="编辑成员" :visible.sync="dlgform.dialogFormVisible" v-loading.fullscreen.lock="loading" :close-on-click-modal="false" width="600px">
      <el-form ref="dlgform" :model="dlgform" label-width="120px">
        <el-form-item label="成员角色" prop="role">
          <el-select v-model="dlgform.role" placeholder="请分配角色" class="wl-input">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDlgForm()" type="primary">确 定</el-button>
        <el-button @click="dlgform.dialogFormVisible=false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getProject, addProjectMember } from '@/api/project'
import { getSpaceMembers } from '@/api/space'

export default {
  name: 'MemberProject',
  data() {
    return {
      loading: false,
      context: {}, // 父页面传递过来的参加，返回时带给父页面恢复上下文
      id: '',
      spaceId: '',
      mbform: {
        userId: '',
        role: ''
      },
      mbformRules: {
        userId: [{ required: true, message: '请选择用户名', trigger: 'blur' }],
        role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      roleOptions: [
        { value: 'MASTER', label: '项目管理员' },
        { value: 'DEVELOPER', label: '开发者'},
        { value: 'REPORTER', label: '访客'}
      ],
      dlgform: {
        dialogFormVisible: false,
        role: '',
        row: ''
      },
      userList: [],  // 添加项目成员下拉列表
      members:[], // 项目成员
      enableUpdate: false,
      enableDelete: false
    }
  },
  mounted() {
    const params = this.$route.params
    this.id = params.id
    this.context = params.context
    this.getProjectInfo()
  },
  methods: {
    handleBack() {
      this.$router.replace({name:'WalleProject', params: this.context})
    },
    handleFocusUsers(query) {
      this.getUserList(200)
    },
    handleInputUserName(e) {
      this.getUserList(200, 1, e.target.value.trim())
    },
    handleAddProjectMember() { // 添加项目成员
      this.$refs.mbform.validate((valid) => {
        if (valid) {
          this.loading = true
          let members = this.members.concat([{user_id: this.mbform.userId, role: this.mbform.role}])
          addProjectMember(this.id, members).then(response => {
            this.loading = false
            if (!response.data || response.data.code !== 0) {
              this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
              return
            }
            this.mbform.userId = ''
            this.mbform.role = ''
            this.$message({ type:'success', message:'添加成功!' })
            this.getProjectInfo()
          }).catch(error => {
            this.loading = false
            this.$message({ type:'error', message:'请求异常！'})
            console.log(error)
          })
        }
      })
    },
    handleEdit(row) { // 编辑
      this.dlgform.role = row.role
      this.dlgform.row = row
      this.dlgform.dialogFormVisible = true
    },
    handleDelete(row) { // 删除
      this.$confirm('确定从项目成员中移除【' + row.username + '】吗?', '提示', {type:'warning', confirmButtonText:'确定', cancelButtonText:'取消'}).then(() => {
        let membs = []
        for (let i in this.members) {
          if (this.members[i].id === row.id) {
            continue
          }
          membs.push({...this.members[i]})
        }
        addProjectMember(this.id, membs).then(response => {
          this.loading = false
          if (!response.data || response.data.code !== 0) {
            this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
            return
          }
          this.getProjectInfo()
          this.$message({ type:'success', message:'成功!' })
        }).catch(error => {
          this.loading = false
          this.$message({ type:'error', message:'请求异常！'})
          console.log(error)
        })
      })
    },
    submitDlgForm() { // 编辑用户角色
      let membs = JSON.parse(JSON.stringify(this.members))
      for (let i in membs) {
        if (membs[i].id === this.dlgform.row.id) {
          membs[i].role = this.dlgform.role
          break
        }
      }
      addProjectMember(this.id, membs).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        this.dlgform.row = ''
        this.dlgform.role = ''
        this.dlgform.dialogFormVisible = false
        this.getProjectInfo()
        this.$message({ type:'success', message:'修改成功!' })
      }).catch(error => {
        this.loading = false
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    },
    getProjectInfo() { // 获取单个项目信息
      this.loading = true
      this.spaceId = ''
      this.members = []
      this.enableUpdate = false
      this.enableDelete = false
      getProject(this.id).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        let data = response.data.data
        this.spaceId = data.space_id
        this.members = data.members
        this.enableUpdate = data.enable_delete
        this.enableDelete = data.enable_update
      }).catch(error => {
        this.loading = false
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    },
    getUserList(size, page, query) {  // 获取可以添加到项目的用户
      this.userList = []
      getSpaceMembers(this.spaceId, size, page, query).then(response => {
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        const data = response.data.data
        let tmplist = []
        for(let i in data.list) {
          let flag = true
          for(let j in this.members) {
            if (data.list[i].username === this.members[j].username) {
              flag = false
              break;
            }
          }
          if (flag) {
            tmplist.push(data.list[i])
          }
        }
        this.userList = tmplist
      }).catch(error => {
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    },
    getMemberRole(role) { //获取成员角色名称
      switch(role) {
        case 'MASTER': return '项目管理员'
        case 'DEVELOPER': return '开发者'
        case 'REPORTER': return '访客'
        default: return role
      }
    }
  }
}
</script>

<style scoped>
  .wl-back {
    color: #1890ff;
    font-size: 14px;
    margin-bottom: 15px;
    cursor: pointer;
  }
  .wl-card {
    margin-bottom: 20px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .wl-append {
    margin-left: 15px;
  }
  .wl-input {
    width: 250px;
  }
  .wl-right {
    float: right;
  }
  .wl-table {
    width:100%;
    margin-top: 10px;
  }
  .wl-avatar {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
  }
  .wl-avatar img {
    width: 30px;
    height: 30px;
    border-radius: 30px;
    display: block;
  }

</style>